let count = 0;
const tree = function (ctx, sx, sy, length, angle, depth, width_branch) {
    let rand = Math.random, n_length, n_angle, n_depth, max_branch = 4, ex, ey, max_angle = 2 * Math.PI / 4;
    let subbranch;
    ctx.beginPath();
    ctx.moveTo(sx, sy);
    ex = sx + length * Math.cos(angle);
    ey = sy + length * Math.sin(angle);
    ctx.lineCap = 'round';
    ctx.lineWidth = width_branch;
    ctx.lineTo(ex, ey);
    if (depth <= 2) {
        //树的枝干
        ctx.strokeStyle = 'rgb(0,' + (((rand() * 64) + 128) >> 0) + ',0)';
    } else {
        //树的叶子
        ctx.strokeStyle = 'rgb(0,' + (((rand() * 64) + 64) >> 0) + ',50,25)';
    }
    ctx.stroke();
    n_depth = depth - 1;
    //判断树是否结束
    if (!n_depth) {
        count++;
        return;
    }
    subbranch = (rand() * (max_branch - 1)) + 1;
    width_branch *= 0.5;
    for (let i = 0; i < subbranch; i++) {
        n_angle = angle + rand() * max_angle - max_angle * 0.5;
        n_length = length * (0.5 + rand() * 0.5);
        setTimeout(function () {
            tree(ctx, ex, ey, n_length, n_angle, n_depth, width_branch);
        }, 1000);
    }
};

const canvas1 = document.getElementById('can');
const context = canvas1.getContext('2d');
//初始化树
init_tree();

function init_tree() {
    tree(context, 300, 700, 150, -Math.PI / 2.1, 8, 30);
    tree(context, 300, 700, 150, -Math.PI / 2.1, 8, 30);
    tree(context, 300, 700, 150, -Math.PI / 2.1, 9, 30);
}

function reset() {
    console.log('count', count);
    if (count > 10000) {
        context.clearRect(0, 0, canvas1.height, canvas1.height);
        count = 0;
        setTimeout(init_tree, 1000);
    }
}

setInterval(reset, 3000);